package com.cht.commonUtil.quartz;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.enums.QuartzJobStatus;
import com.cht.commonUtil.structure.I2L1S4;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class QueryExistingJob extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType( "application/json" );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		List<I2L1S4> qzjs = new ArrayList<I2L1S4>();
		
		String subsysId = request.getParameter("subsysId");
		String sql = "SELECT t1.quartzJobId,t1.quartzId,t2.quartzJobTypeId,t2.quartzJobTypeDesc,t1.cronString,t1.cronStringDesc,t3.empName,t1.cDT FROM quartzjob t1,quartzjobtype t2,emps t3 WHERE t1.creator=t3.empId AND t1.quartzJobTypeId=t2.quartzJobTypeId AND subsysId=? AND status=?";
		
		try {
			conn = Widgets.getConn();	
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setInt(2, QuartzJobStatus.ACTIVATED );
			rs = ps.executeQuery();
			while( rs.next() ) {
				I2L1S4 qzj = new I2L1S4();
				qzj.setI1( rs.getInt("quartzJobId") );	//排程ID
				qzj.setI2( rs.getInt("quartzJobTypeId") );
				qzj.setL1( rs.getLong("quartzId") );
				qzj.setS1( rs.getString("quartzJobTypeDesc") );	//排程類型
				qzj.setS2( rs.getString("cronString") );	//排程公式
				qzj.setS3( rs.getString("empName") );	//創建人員
				qzj.setS4( Widgets.changeTimeFormat( rs.getTimestamp("cDT") ) );
				qzjs.add(qzj);
			}
		} catch ( Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) { e.printStackTrace(); }
		}
		response.getWriter().write(new Gson().toJson(qzjs));	
	}
}
